package com.tanhua.server.service;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.api.SoundApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.pojo.Sound;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.server.vo.SoundVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;

@Service
public class SendSoundService {

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private FastFileStorageClient client;

    @DubboReference(version = "1.0.0")
    private SoundApi soundApi;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    /**
     * 发送语音
     *
     * @param soundFile
     * @return
     */
    public Object sendSound(MultipartFile soundFile) {

        try {
            //上传oss中
            PicUploadResult uploadResult = this.picUploadService.upload(soundFile);

            if (StrUtil.isEmpty(uploadResult.getName())) {
                return ErrorResult.builder().errCode("500")
                        .errMessage("上传音频失败，请重试！").build();
            }

            String fileExtName = StrUtil.subAfter(soundFile.getOriginalFilename(), '.', true);
            StorePath storePath = this.client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), fileExtName, null);
            //语音的路径
            String soundUrl = this.fdfsWebServer.getWebServerUrl() + storePath.getFullPath();

            //sound
            Sound sound = new Sound();
            sound.setSoundUrl(soundUrl);
            sound.setUserId(UserThreadLocal.get());
            sound.setCreated(System.currentTimeMillis());
            //调用api保存sound
            this.soundApi.save(sound);
        } catch (IOException e) {
            return ErrorResult.builder().errCode("501")
                    .errMessage("上传语音文件失败，请重试！").build();
        }

        return null;
    }

    /**
     * 接受语音
     *
     * @return
     */
    public Object getSound() {
        Long userId = UserThreadLocal.get();
        String key = "remainingTimes_" + userId;

        //Integer times = (Integer) this.redisTemplate.opsForValue().get(key);
        Integer times =Convert.toInt(this.redisTemplate.opsForValue().get(key));

        if (null == times) {
            this.redisTemplate.opsForValue().set(key, "10", Duration.ofDays(1));
            //times = (Integer) this.redisTemplate.opsForValue().get(key);
            times =Convert.toInt(this.redisTemplate.opsForValue().get(key));
        }
        if (times <= 0) {
            //次数用完
            return ErrorResult.builder().errCode("500").errMessage("次数已用完").build();
        }

        Sound highScoreSound = this.soundApi.getHighScoreSound(userId);

        if (null == highScoreSound.getSoundUrl()) {
            return ErrorResult.builder().errCode("500").errMessage("次数已用完").build();
        }

        UserInfo userInfo = this.userInfoApi.queryByUserId(highScoreSound.getUserId());
        //封装返回类型
        SoundVo soundVo = new SoundVo();
        soundVo.setSoundUrl(highScoreSound.getSoundUrl());
        soundVo.setId(Convert.toInt(userId));
        soundVo.setAge(userInfo.getAge());
        soundVo.setAvatar(userInfo.getLogo());
        soundVo.setNickname(userInfo.getNickName());
        soundVo.setGender(userInfo.getSex().name().toLowerCase());
        Long timesLong = this.redisTemplate.opsForValue().decrement(key);
        soundVo.setRemainingTimes(Convert.toInt(timesLong));

        return soundVo;
    }

}
